import { useState } from "react";
import { Divider, type FormInstance, Modal } from "antd";
import EditForm from "./edit-form";

import type { EditUserDataType, UserDataType } from "@/types/user";

type EditModalProps = {
  open: boolean;
  onEdit: (values: EditUserDataType) => Promise<unknown>;
  onCancel: () => void;
  initialValues: UserDataType;
};

export default function EditModal({ open, onEdit, onCancel, initialValues }: EditModalProps) {
  const [formInstance, setFormInstance] = useState<FormInstance>();
  const [loading, setLoading] = useState(false);
  return (
    <Modal
      title="编辑用户信息"
      centered
      open={open}
      destroyOnClose
      maskClosable={false}
      onCancel={onCancel}
      confirmLoading={loading}
      okButtonProps={{ htmlType: "submit" }}
      cancelButtonProps={{ disabled: loading }}
      onOk={async () => {
        try {
          const values = await formInstance?.validateFields();
          setLoading(true);
          onEdit(values)
            .then(() => {
              window.$message?.success("编辑成功");
            })
            .catch((error) => {
              window.$message?.error(error.message);
            })
            .finally(() => {
              setLoading(false);
              onCancel();
            });
        } catch (error) {
          console.log("Failed:", error);
        }
      }}
    >
      <Divider style={{ margin: "0" }} />
      <EditForm
        initialValues={initialValues}
        onFormInstanceReady={(form) => {
          setFormInstance(form);
        }}
      />
    </Modal>
  );
}
